from django.shortcuts import render
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from django.http import JsonResponse
from account.forms import *


# Create your views here.

def login(request):
    login_form = LoginForm()
    if request.method == 'GET':
        context = {
            'login_form': login_form,
        }
        return render(request, 'account/login.html', context)

    else:
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user:
            request.session['is_login'] = True
            return JsonResponse({'status': 'success'})
        else:
            error_field = []
            if User.objects.filter(username=username).exists():
                error_field.append('password')
            else:
                error_field.append('username')

            context = {
                'status': 'failed',
                'error_field': error_field
            }
            return JsonResponse(context)
